package com.qingcheng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qingcheng.pojo.system.Admin;
import com.qingcheng.service.system.AdminService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserDetailsServiceImpl implements UserDetailsService {
    @Reference
    private AdminService adminService;

    /**
     * 登录时用户名校验和权限控制
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Map map=new HashMap();
        //将条件封装进map集合，按用户名和用户状态查询出存在的用户
        map.put("loginName",username);
        map.put("status","1");
        List<Admin> adminList = adminService.findList(map);
        if(adminList.size()==0){
            return null;
        }
        //获取用户对象
        Admin admin = adminList.get(0);
        Integer id = admin.getId();

        //创建集合用以封装权限字符串
        List<GrantedAuthority> grantedAuthorityList=new ArrayList<GrantedAuthority>();

        //给所有登录成功的用户添加此角色，此角色对应的资源是所有去权限并放在最后，防止一些资源访问不到
        grantedAuthorityList.add(new SimpleGrantedAuthority("ROLE_USER"));

        //根据id查询用户对应权限
        List<String> resources = adminService.findAllResourceId(id);
        if(resources.size()!=0){
            //遍历权限集合，就权限逐一添加到集合
            for (String resource : resources) {
                grantedAuthorityList.add(new SimpleGrantedAuthority(resource));
            }
        }

        //将用户信息传递给security框架进行处理
        return new User(username,admin.getPassword(),grantedAuthorityList);
    }
}
